#!/usr/bin/env node

/**
 * 📦 版本号批量更新工具
 * 
 * 使用方法：
 *   node scripts/bump-version.js [package-name] [version-type]
 * 
 * 示例：
 *   node scripts/bump-version.js core-token patch    # 1.0.0 → 1.0.1
 *   node scripts/bump-version.js network-http minor  # 1.0.0 → 1.1.0
 *   node scripts/bump-version.js all patch           # 所有包 +0.0.1
 */

import { readFileSync, writeFileSync, readdirSync } from 'fs'
import { join } from 'path'
import { fileURLToPath } from 'url'
import { dirname } from 'path'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const ROOT_DIR = join(__dirname, '..')

const args = process.argv.slice(2)
const packageName = args[0]
const versionType = args[1] || 'patch' // patch, minor, major

if (!packageName) {
  console.log('❌ 请指定包名或 all')
  console.log('使用方法: node scripts/bump-version.js [package-name] [patch|minor|major]')
  console.log('示例: node scripts/bump-version.js core-token patch')
  console.log('     node scripts/bump-version.js all patch')
  process.exit(1)
}

/**
 * 升级版本号
 */
function bumpVersion(version, type) {
  const [major, minor, patch] = version.split('.').map(Number)
  
  switch (type) {
    case 'major':
      return `${major + 1}.0.0`
    case 'minor':
      return `${major}.${minor + 1}.0`
    case 'patch':
    default:
      return `${major}.${minor}.${patch + 1}`
  }
}

/**
 * 更新 package.json 版本号
 */
function updatePackageVersion(pkgPath) {
  const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'))
  const oldVersion = pkg.version
  const newVersion = bumpVersion(oldVersion, versionType)
  
  pkg.version = newVersion
  writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n')
  
  console.log(`  ✅ ${pkg.name}: ${oldVersion} → ${newVersion}`)
  return { name: pkg.name, oldVersion, newVersion }
}

/**
 * 查找包目录
 */
function findPackages() {
  const packagesDir = join(ROOT_DIR, 'tuxing-packages')
  const packages = []
  
  function scan(dir) {
    const categories = readdirSync(dir)
    for (const cat of categories) {
      const catPath = join(dir, cat)
      try {
        const items = readdirSync(catPath)
        for (const item of items) {
          const itemPath = join(catPath, item)
          const pkgPath = join(itemPath, 'package.json')
          try {
            const stat = require('fs').statSync(pkgPath)
            if (stat.isFile()) {
              packages.push({ path: pkgPath, name: item })
            }
          } catch (e) {
            // 没有 package.json，跳过
          }
        }
      } catch (e) {
        // 不是目录，跳过
      }
    }
  }
  
  scan(packagesDir)
  return packages
}

/**
 * 更新所有微应用中的依赖版本
 */
function updateMicroAppDeps(pkgName, newVersion) {
  const microAppsDir = join(ROOT_DIR, 'micro-apps')
  const apps = readdirSync(microAppsDir)
  
  let count = 0
  for (const app of apps) {
    const pkgPath = join(microAppsDir, app, 'package.json')
    try {
      const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'))
      let modified = false
      
      // 更新 dependencies
      if (pkg.dependencies && pkg.dependencies[pkgName]) {
        pkg.dependencies[pkgName] = `workspace:^${newVersion}`
        modified = true
      }
      
      // 更新 devDependencies
      if (pkg.devDependencies && pkg.devDependencies[pkgName]) {
        pkg.devDependencies[pkgName] = `workspace:^${newVersion}`
        modified = true
      }
      
      if (modified) {
        writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n')
        count++
      }
    } catch (e) {
      // 没有 package.json，跳过
    }
  }
  
  return count
}

// 主逻辑
console.log(`\n🚀 版本升级工具 - ${versionType.toUpperCase()}\n`)

const packages = findPackages()
const updatedPackages = []

if (packageName === 'all') {
  console.log('📦 更新所有包的版本号...\n')
  for (const pkg of packages) {
    const result = updatePackageVersion(pkg.path)
    updatedPackages.push(result)
  }
} else {
  console.log(`📦 更新包: ${packageName}\n`)
  const targetPkg = packages.find(p => p.name === packageName)
  
  if (!targetPkg) {
    console.log(`❌ 找不到包: ${packageName}`)
    console.log('可用的包:')
    packages.forEach(p => console.log(`  - ${p.name}`))
    process.exit(1)
  }
  
  const result = updatePackageVersion(targetPkg.path)
  updatedPackages.push(result)
}

// 更新微应用中的依赖
console.log('\n📱 更新微应用中的依赖版本...\n')
for (const pkg of updatedPackages) {
  const count = updateMicroAppDeps(pkg.name, pkg.newVersion)
  if (count > 0) {
    console.log(`  ✅ ${pkg.name}: 更新了 ${count} 个微应用`)
  }
}

console.log('\n✅ 版本更新完成！\n')
console.log('💡 接下来：')
console.log('  1. git add .')
console.log(`  2. git commit -m "chore: bump version to ${updatedPackages[0]?.newVersion}"`)
console.log('  3. pnpm -r build\n')

